#include<iostream>
#include <sys/types.h>  //mkfifo的头文件open头文件
#include<string>
#include <sys/stat.h>   //mkfifo的头文件open头文件

#include <unistd.h>     //unlink头文件/close头文件
#include <fcntl.h>      //open头文件



using namespace std;
const string com_path="./myfifo";
#define Defaultfd -1
#define Creater 1
#define User 2
#define Read O_RDONLY
#define Write O_WRONLY
#define Basesize 1024
class Namepipe
{
   private:
   bool opennamepipe(int mode)
   {
   _fd=open(_fifo_path.c_str(),mode);
   if(_fd<0)
    return false;
    return true;
   }
public: 
Namepipe(const string &path,int who)
:_fifo_path(path)
,_id(who)
,_fd(Defaultfd)
{
 
 if(_id==Creater)
 {
  int ret=mkfifo(_fifo_path.c_str(),0666);
     if(ret!=0)
       {
        perror("mkfifo");


       }

       cout<<"creater create named pipe"<<endl;
 }
}
~Namepipe()
{

if(_id==Creater)
{
 int ret=unlink(_fifo_path.c_str());
 if(ret!=0)
    {
    perror("unlink");
    }
    cout<<"creater free namepipe"<<endl;
}
if(_fd!= Defaultfd)close(_fd);
}
bool openforread()
{

return opennamepipe(Read);


}

bool openforwrite()
{
return opennamepipe(Write);
}



int writenamepipe(const string &in)
{

 return write(_fd,in.c_str(),in.size());
}



int readnamepipe(string *out)
{
char buffer[Basesize];
int n=read(_fd,buffer,sizeof(buffer));
if(n>0)
{buffer[n]=0;
*out=buffer;
}
return n;
}

private:
     const string _fifo_path;
     int _id;
     int _fd;
};